package design_pattern.singleton;

/**
 * 饿汉式，通过静态私有成员变量，类加载直接创建，所以饿汉式
 */

public class SingletonTest1 {
    public static void main(String[] args) {
        // 测试
        Singleton1 instance1 = Singleton1.getInstance();
        Singleton1 instance2 = Singleton1.getInstance();
        System.out.println(instance1 == instance2);
        System.out.println("instance1.hashCode="+instance1.hashCode());
        System.out.println("instance2.hashCode="+instance2.hashCode());
    }

}
class Singleton1{
    // 1. 构造器私有化，防止通过new Singleton()的方式创建对象
    private Singleton1(){ }
    // 2. 类内部创建对象实例私有成员变量，类加载直接创建，所以饿汉式
    private final static Singleton1 instance = new Singleton1();
    // 3. 提供公有静态方法，返回该实例对象
    public static Singleton1 getInstance(){
        return instance;
    }
}





